const http = require('http')
const fs = require('fs')
const path = require('path')

http.createServer((req,res)=>{
    if(req.url=="/"){
        var fileContent = fs.readFileSync('./upload.html')
        res.writeHead(200,{"Content-Type":"text/html;charset=utf8"})
        res.end(fileContent)
    }else{
        var str = ''
        req.setEncoding('binary')
        req.on("data",(chunk)=>{
            str += chunk
        })
        req.on("end",()=>{
            var arr = str.split('\r\n')
            var imgArr = arr.slice(4,arr.length - 2)
            var imgStr = imgArr.join('\r\n')
            var buf = Buffer.from(imgStr,"binary")
            fs.writeFileSync(path.join(__dirname,'/img/1.png'),buf,{"encoding":"binary"})
        })
    }
}).listen(8081)
console.log("server is listening 8081")